# -*- coding: utf-8 -*-

from datetime import datetime
from flask import redirect, url_for, request, render_template, render_template_string, Response
import requests
import uuid
import logging
import random
import os
import json

from meiriyitu.models import User, Content, Joke_content, Content_image_urls, Calendar_Memo
from meiriyitu import db
from meiriyitu.util import *

from sqlalchemy.sql import func

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s: %(message)s')

APPID = "wx66dc574f6aec96da"
APPSECRET = "15756d960db3038b003b2f82add2b71d"

# 获取userid
# 获取openid,session_key

def beian():
    return """
    <p>"这是一个微信小程序！"</p>
    <div style="width:300px;margin:0 auto; padding:20px 0;">
		 		<a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=31011202012885" 
		 		style="display:inline-block;text-decoration:none;height:20px;line-height:20px;">
		 		<img src="https://sunsun.vip/image/beian" style="float:left;"/>
		 		<p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; 
		 		color:#939393;">沪公网安备 31011202012885号</p>
		 		</a>
		 	</div>
		 
    """



def jscode():
    global getuserid

    JSCODE = request.form.get('js_code') or request.values.get('js_code') or request.json.get('js_code')
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={APPSECRET}&js_code={JSCODE}&grant_type=authorization_code'.format(
        APPID=APPID,
        APPSECRET=APPSECRET,
        JSCODE=JSCODE
     )
    getuserid = {}
    response = requests.get(url)
    data = response.json()
    openid = data['openid']
    session_key = data['session_key']
    time = datetime.now()
    # 第一次登录openid为空的时候,创建userid并返回userid
    if User.query.filter_by(openid=openid).first() is None:
        userid = str(uuid.uuid4())
        data['userid'] = userid
        user = User(userid=userid, first_login_time=time, openid=openid, session_key=session_key)
        db.session.add(user)
        db.session.commit()
        getuserid['getuserid'] = userid
        logging.info('第一次登录')
        return getuserid
    # 非第一次登录，根据解析而出的openid获取userid并返回
    else:
        # print(openid)
        User.query.filter_by(openid=openid).update(
            {'last_login_time': time,
             'session_key': session_key,
             'login_times': User.login_times + 1}
        )
        db.session.commit()
        user = User.query.filter_by(openid=openid).first()
        getuserid['getuserid'] = user.userid
        logging.info('非第一次登录')
        logging.info(getuserid)
        logging.info(type(getuserid))
        return getuserid


def get_userid():
    data = getuserid
    logging.info('js获取的data',data)
    return data

# 获取access_token
def get_access_token():
    url = ' https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(APPID,
                                                                                                            APPSECRET)
    res = requests.get(url)
    access_token = res.json()
    access_token = access_token['access_token']
    return access_token


def get_openid():
    try:
        userid = request.form.get('userid') or request.values.get('userid') or request.json.get('userid')
        openid = User.query.filter_by(userid=userid).first()
        return openid
    except:
        print('没找到userid')
    return openid

# 首页
def index():
        # 随机取10条
        # 根据t_id 作为条件
        index = 0
        content = {}
        max = db.session.query(func.max(Joke_content.t_id)).first()
        max = list(max)[0]
        while index < 10:
            t_id = random.randint(1, max)
            con = Joke_content.query.filter_by(t_id=t_id).first()
            if con:
                if con.body != '查看全文':
                    time = con.create_time.strftime('%Y-%m-%d %H:%M:%S')
                    content[index] = {'body': con.body, 'datetime': time, 't_id':con.t_id}
                    index += 1
                else:
                    continue
        return content

# 留言功能
# 分为post和get两种方式，首次是get方法，之后用post方法，获取分页
# 首先从数据库获取所有在进行分段获取
def message():

    cons = Content.query.order_by(Content.create_time.desc()).all()

    def search_content(index, pageNum):
        content = {}
        size = 10
        num = len(cons) % size
        print(len(cons))
        if pageNum * size <= len(cons) + size:
            while index < pageNum * size:
                if index == len(cons):
                    break
                print(pageNum, index)
                con = cons[index]
                time = con.create_time.strftime('%Y-%m-%d %H:%M:%S')
                con_url = Content_image_urls.query.filter_by(content_name=con.content_name).first()
                if con_url:
                    content[index] = {'imgurl': con_url.img_url, 'author': con.author.nickname, 'body': con.body, 'datetime': time, \
                                      't_id': con.t_id, 'watch': con.watch}

                else:
                    content[index] = {'author': con.author.nickname, 'body': con.body, 'datetime': time, \
                                      't_id': con.t_id, 'watch': con.watch}
                index += 1
            return content

    if request.method == 'GET':
        pageNum = 1
        index = 0
        content = search_content(index, pageNum)
        return content

    if request.method == 'POST':
        pageNum = int(request.form.get('pageNum') or request.values.get('pageNum') or request.json.get('pageNum'))
        index = int(request.form.get('index') or request.values.get('index') or request.json.get('index'))
        if index > len(cons):
            return('nodata')
        else:
            content = search_content(index, pageNum)
            return content





# 备用！！！！！！！！！！！！！！！
# def message():
#     if request.method == 'GET':
#         cons = Content.query.all()
#         content = {}
#         for index, con in enumerate(cons):
#             print(con)
#             time = con.create_time.strftime('%Y-%m-%d %H:%M:%S')
#             content[index] = {'title': con.title, 'author': con.author.nickname, 'body': con.body, 'datetime': time,\
#                               't_id':con.t_id}
#         return content

# 保存昵称
def get_userinfo():
    userid = request.form.get('userid') or request.values.get('userid') or request.json.get('userid')
    nickname = request.form.get('nickname') or request.values.get('nickname') or request.json.get('nickname')
    User.query.filter_by(userid=userid).update({'nickname': nickname})
    db.session.commit()
    return nickname

# 输入文字
def write_content():
    title = request.form.get('title') or request.values.get('title') or request.json.get('title')
    content = request.form.get('content') or request.values.get('content') or request.json.get('content')
    userid = request.form.get('userid') or request.values.get('userid') or request.json.get('userid')
    c = Content(title=title, body=content, userid=userid, create_time=datetime.now())
    db.session.add(c)
    db.session.commit()
    print(title, content, userid)
    return userid

# 选择文章页面
def select_content():
    t_id = request.form.get('t_id') or request.values.get('t_id') or request.json.get('t_id')
    con = Content.query.filter_by(t_id=t_id).first()
    Content.query.filter_by(t_id=t_id).update({'watch': Content.watch + 1})
    db.session.commit()
    print(t_id,'\n',con)
    time = con.create_time.strftime('%Y-%m-%d %H:%M:%S')
    con_urls = Content_image_urls.query.filter_by(content_name=con.content_name).all()
    urls = []
    for con_url in con_urls:
        img_url = con_url.img_url
        urls.append(img_url)
    print(urls)
    content = { 'author': con.author.nickname, 'body': con.body, 'datetime': time, 't_id':con.t_id, 'con_url': urls}
    return content

# 显示图片
def show_image(image):

    data_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
    data_next_path = os.path.join(data_path, 'images')
    print(data_next_path)
    file_dir = os.path.join(data_next_path, image + '.jpg')
    image_data = open(file_dir, 'rb')
    picture = Response(image_data, mimetype="image/jpeg")
    return picture

# 上传图片/文章
def add_content_and_up_image():
    f = request.files['file']
    imagename = request.values.get('imagename')
    byte_to_image(f, imagename)
    userid = request.values.get('userid')
    content = request.values.get('content')
    date = datetime.now().strftime('%Y%m%d')
    content_name = userid[0:10] + content[0:10] + date
    image_url = 'https://sunsun.vip/upimage/' + imagename
    print(userid, content)
    print(image_url)
    # print(type(f))
    # img = f.read()
    # print(img)
    con = Content.query.filter_by(content_name=content_name).first()
    if con is None:
        c = Content(body=content, userid=userid, create_time=datetime.now(), content_name=content_name)
        cu = Content_image_urls(userid=userid, content_name=content_name, img_url=image_url)
        db.session.add(c)
    else:
        cu = Content_image_urls(userid=userid, content_name=content_name, img_url=image_url)
    db.session.add(cu)
    db.session.commit()
    print(content, userid)
    print(imagename ,userid)

    return '传输成功'



# 查看上传图片
def uploadimage(image):
    data_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
    data_next_path = os.path.join(data_path, 'upimage')
    print(data_next_path)
    file_dir = os.path.join(data_next_path, image)
    image_data = open(file_dir, 'rb')
    picture = Response(image_data, mimetype="image/jpeg")
    return picture

def top_images():
    imgurldb = Content_image_urls.query.order_by(Content_image_urls.create_time.desc()).all()
    imgurls = []
    for imgurl in imgurldb:
        url = imgurl.img_url
        imgurls.append(url)
    urls = imgurls[0:5]
    images = {'imgurls': urls}
    return images

# 日历备忘录
# 读取日历备忘录
def read_calendar_memo():
    userid = request.form.get('userid') or request.values.get('userid') or request.json.get('userid')

    memos = Calendar_Memo.query.filter_by(userid=userid).all()
    res = {}
    for index,memo in enumerate(memos):
        res[index] = memo.to_json()
    print(res)
    print(type(res))

    return res

# 写入日历备忘录
def write_calendar_memo():
    title = request.form.get('title') or request.values.get('title') or request.json.get('title')
    memo = request.form.get('memo') or request.values.get('memo') or request.json.get('memo')
    userid = request.form.get('userid') or request.values.get('userid') or request.json.get('userid')
    start_date = request.form.get('start_date') or request.values.get('start_date') or request.json.get('start_date')
    start_time = request.form.get('start_time') or request.values.get('start_time') or request.json.get('start_time')
    finish_date = request.form.get('finish_date') or request.values.get('finish_date') or request.json.get('finish_date')
    finish_tiem = request.form.get('finish_time') or request.values.get('finish_time') or request.json.get('finish_time')
    isfinish = request.form.get('isfinish') or request.values.get('isfinish') or request.json.get('isfinish')
    level = request.form.get('level') or request.values.get('level') or request.json.get('level')
    start_datetime = start_date + ' ' + start_time
    finish_datetime = finish_date + ' ' + finish_tiem
    c = Calendar_Memo(
        memo=memo,
        userid=userid,
        start_datetime=start_datetime,
        finish_datetime=finish_datetime,
        isfinish=int(isfinish),
        level=int(level),
        create_time=datetime.now()
    )
    db.session.add(c)
    db.session.commit()
    print(title, memo, userid ,start_datetime,datetime.now())
    return userid





